import IDBM from '../lib/IndexedDBManage'

export default {
    data() {
        return {
            yyymfwSel: false
        }
    },
    computed: {
        basin() {
            return this.$store.getters.basin
        }
    },
    destroyed() {
        this.clearYYYMFW()
    },
    created() {
        var colors05 = this.gradient('#00A2FB', '#F0C90B', 20)
        var colors51 = this.gradient('#F0C90B', '#F0810B', 20)
        var colors12 = this.gradient('#F0810B', '#CE1F1F', 20)
        this.colorAll = [...colors05, ...colors51, ...colors12]
        this.dataSourceYYYMFW = null
        this.$eventBus.$on('YYFXPG', e => {
            if (e) {
                this.yyymfwSel = true
                this.getMeshYYYMFW()
            } else {
                this.yyymfwSel = false
                this.clearYYYMFW()
            }
        })
    },
    mounted() {
        this.$nextTick(() => {
            // this.getOutPutTimeList()
        })
    },
    methods: {
        onYYYMFW() {
            this.yyymfwSel = !this.yyymfwSel
            if (this.yyymfwSel) {
                this.getMeshYYYMFW()
            } else {
                this.clearYYYMFW()
            }
        },
        getPoints(basin, refresh = false) {
            return new Promise((resolve, reject) => {
                IDBM.readPoint(basin).then(res => {
                    console.log(res)
                    if (res && !refresh) {
                        resolve(res)
                    } else {
                        var lonlats = []
                        this.$axios.get('/mapData/guangdong/txt/point.txt').then(resPoint => {
                            var pointRows = resPoint.data.split('\r\n')
                            var maxLon = 0
                            var minLon = 180
                            var maxLat = 0
                            var minLat = 90
                            pointRows.forEach(lonlatstr => {
                                var oneLonlat = lonlatstr.split(',')
                                if (oneLonlat && oneLonlat.length > 1) {
                                    maxLon = maxLat > Number(oneLonlat[0]) ? maxLon : Number(oneLonlat[0])
                                    minLon = minLon < Number(oneLonlat[0]) ? minLon : Number(oneLonlat[0])
                                    maxLat = maxLat > Number(oneLonlat[1]) ? maxLat : Number(oneLonlat[1])
                                    minLat = minLat < Number(oneLonlat[1]) ? minLat : Number(oneLonlat[1])
                                    lonlats.push([Number(oneLonlat[0]), Number(oneLonlat[1])])
                                }
                            })

                            // 正方形UV
                            var sub = (maxLon - minLon) - (maxLat - minLat)
                            if (sub > 0) {
                                maxLat = maxLat + sub / 2
                                minLat = minLat - sub / 2
                            } else {
                                maxLon = maxLon - sub / 2
                                minLon = minLon + sub / 2
                            }
                            maxLon = maxLon + 0.0005
                            minLon = minLon - 0.0005

                            if (isNaN(maxLon) || isNaN(minLon) || isNaN(maxLat) || isNaN(minLat)) {
                                console.log('没有点表坐标的最大最小值')
                                this.getPoints(basin, true)
                            }
                            IDBM.writePoint({ basin, lonlats, maxLon, minLon, maxLat, minLat })
                            resolve({ basin, lonlats, maxLon, minLon, maxLat, minLat })
                        })
                    }
                })
            })
        },
        getMeshs(basin) {
            return new Promise((resolve, reject) => {
                IDBM.readMeshOut(basin).then(res => {
                    if (res) {
                        resolve(res)
                    } else {
                        var pointIndexs = []
                        this.$axios.get('/mapData/guangdong/txt/mesh.txt').then(resMesh => {
                            var meshs = resMesh.data.split('\r\n')
                            // meshs = meshs.slice(0, 10)
                            meshs.forEach(item => {
                                var oneRow = item.split(',')
                                pointIndexs.push(oneRow)
                            })
                            IDBM.writeMesh({ basin, pointIndexs })
                            resolve({ basin, pointIndexs })
                        })
                    }
                })
            })
        },
        getOutPutTimeList(planID) {
            // planID = '1a7c27cd-e970-4ebd-9911-2737ea652dc6'

            return new Promise((resolve, reject) => {
                IDBM.readPlanOneTime(planID, 'allTime').then(res => {
                    if (res) {
                        resolve(res.meshs)
                    } else {
                        var getPoint = this.getPoints(this.basin, '/mapData/guangdong/txt/point.txt')
                        var getMesh = this.getMeshs(this.basin)
                        // debugger
                        var getApi = this.$api.Get('/api/CalcPreview/GetMaxDrowning', {
                            ID: planID
                            // ID: this.planCurrSel.id
                        }, 'GetMaxDrowning')
                        Promise.all([getPoint, getMesh, getApi]).then(([resPoint, resMesh, resApi]) => {
                            console.log(resApi)
                            var colorIndex = 3
                            var meshToSave = []
                            resApi.data.forEach(item => {
                                if (item.h > 2) {
                                    colorIndex = 59
                                } else if (item.h > 1) {
                                    colorIndex = Math.round(item.h * 20 - 20) + 39
                                } else if (item.h > 0.5) {
                                    colorIndex = Math.round((item.h - 0.5) * 0.4 * 100) + 20
                                } else {
                                    colorIndex = Math.round(item.h * 0.4 * 100)
                                }
                                const pointIndex = resMesh.pointIndexs[Number(item.guid)]
                                const lonlats = []
                                pointIndex.forEach(jtem => {
                                    const lonlat = resPoint.lonlats[Number(jtem)]
                                    lonlats.push(...lonlat)
                                })
                                const cartesian3 = Cesium.Cartesian3.fromDegreesArray(lonlats)
                                meshToSave.push({ guid: item.guid, tm: item.tm, h: item.h, cartesian3, colorIndex })
                            })
                            IDBM.writePlan(planID, { time: 'allTime', meshs: meshToSave })
                            resolve(meshToSave)
                        })
                    }
                })
            })
        },
        // rgb to hex
        rgbToHex(r, g, b) {
            var hex = ((r << 16) | (g << 8) | b).toString(16)
            return '#' + new Array(Math.abs(hex.length - 7)).join('0') + hex
        },
        // hex to rgb
        hexToRgb(hex) {
            var rgb = []
            for (var i = 1; i < 7; i += 2) {
                rgb.push(parseInt('0x' + hex.slice(i, i + 2)))
            }
            return rgb
        },
        // 计算渐变过渡色
        gradient(startColor, endColor, step) {
            // 将 hex 转换为rgb
            var sColor = this.hexToRgb(startColor)
            var eColor = this.hexToRgb(endColor)
            // 计算R\G\B每一步的差值
            var rStep = (eColor[0] - sColor[0]) / step
            var gStep = (eColor[1] - sColor[1]) / step
            var bStep = (eColor[2] - sColor[2]) / step
            var gradientColorArr = []
            for (var i = 0; i < step; i++) {
                // 计算每一步的hex值
                gradientColorArr.push(
                    this.rgbToHex(
                        parseInt(rStep * i + sColor[0]),
                        parseInt(gStep * i + sColor[1]),
                        parseInt(bStep * i + sColor[2])
                    )
                )
            }
            return gradientColorArr
        },
        getMeshYYYMFW() {
            // 是否是风险评估
            if (this.$refs.yyfaxqfxpg && this.$refs.yyfaxqfxpg.$data.selectNum !== 1) return
            this.clearYYYMFW()
            // const colorList = ['#CE1F1F', '#F0810B', '#F0C90B', '#00A2FB']
            this.$store.dispatch('mapLoadingText', ['请求数据...'])
            this.getOutPutTimeList(this.planCurrSel.id).then(meshs => {
                this.dataSourceYYYMFW = new Cesium.CustomDataSource('PolylineDataSource')
                meshs.forEach(item => {
                    const color = Cesium.Color.fromCssColorString(this.colorAll[item.colorIndex])
                    var polyEntity = {
                        eventName: '最大淹没范围',
                        prop: item,
                        polygon: {
                            hierarchy: item.cartesian3,
                            // perPositionHeight: true,
                            material: color.withAlpha(0.5)
                        }
                    }
                    this.dataSourceYYYMFW.entities.add(polyEntity)
                })
                this.$viewer.dataSources.add(this.dataSourceYYYMFW)
                this.$store.dispatch('mapLoadingText', [])
                this.$eventBus.$emit('openLayer', 'DMX')
                this.$eventBus.$emit('DMXRehearsalID', this.planCurrSel.id)
                this.initEventYYYMFW()
                // this.$viewer.camera.flyTo({
                //     duration: 1,
                //     easingFunction: Cesium.EasingFunction.LINEAR_NONE,
                //     destination: Cesium.Cartesian3.fromDegrees(
                //         109.9774, 34.0711, 7668),
                //     orientation: {
                //         heading: Cesium.Math.toRadians(354),
                //         pitch: Cesium.Math.toRadians(-32),
                //         roll: 0.0
                //     }
                // })
            })
        },
        initEventYYYMFW() {
            var eventFn = pickedObject => {
                if (
                    pickedObject &&
                    pickedObject.id &&
                    pickedObject.id.eventName
                ) {
                    if (pickedObject.id.eventName === '最大淹没范围') {
                        const dlgParams = this.$store.getters.dlgParams
                        dlgParams.name = 'floodDlog'
                        dlgParams.params = { ID: this.planCurrSel.id, Guid: pickedObject.id.prop.guid }
                        this.$store.dispatch('dlgParams', dlgParams)
                    }
                }
            }
            this.$store.getters.eventCesiumOption.leftPickFns.set('最大淹没范围', eventFn)
        },
        clearYYYMFW() {
            if (this.dataSourceYYYMFW) this.$viewer.dataSources.remove(this.dataSourceYYYMFW)
            this.$eventBus.$emit('closeLayer', 'DMX')
            this.$store.getters.eventCesiumOption.leftPickFns.delete('最大淹没范围')
        }
    }
}
